package com.example.blog1.controller;

import com.example.blog1.model.BlogInfo;
import com.example.blog1.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.blog1.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getBlogList")
    public List<BlogInfo> getBloglist() {
        List<BlogInfo> list = blogService.getBlogList();
        for (BlogInfo blogInfo:list) {
            String content = blogInfo.getContent();
            String newContent = content.replace("#","");
            if (newContent.length() > 100) newContent = newContent.substring(0,100) + "...";
            blogInfo.setContent(newContent);
        }
        return list;
    }

    @RequestMapping("/getBlogByBlogId")
    public BlogInfo queryBlogByBlogId(Integer blogId) {
        if (blogId == null || blogId < 0) return null;
        return blogService.queryBlogByBlogId(blogId);
    }

    @RequestMapping("/update")
    public boolean update(String title,String content,Integer blogId) {
        if (!StringUtils.hasLength(title) || !StringUtils.hasLength(content)) return false;
        Integer ret = blogService.update(title,content,blogId);
        if (ret > 0) return true;
        return false;
    }

    @RequestMapping("/add")
    public boolean add(HttpServletRequest request,String title, String content) {
        String token = request.getHeader("user_token");
        Integer userId = JwtUtil.getUserIdFromToken(token);
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setUserId(userId);
        Integer ret = blogService.add(blogInfo);
        if (ret > 0) return true;
        return false;
    }

    @RequestMapping("/delete")
    public boolean delete(Integer blogId) {
        Integer ret = blogService.delete(blogId);
        if (ret > 0) return true;
        return false;
    }
}
